from django.shortcuts import render,HttpResponse

# Create your views here.
import json
from opslog import models
from django.views import View


def getdata(data):
	values = data.META
	try:
		remote_addr = values.get('REMOTE_ADDR', None)
		server_port = values.get('SERVER_PORT', None)
		request_method = values.get('REQUEST_METHOD', None)
		path_info = values.get('PATH_INFO', None)
		url_scheme = values.get('wsgi.url_scheme', None)
		query_string = values.get('QUERY_STRING', None)
		request_body = data.body
		http_user_agent = values.get('HTTP_USER_AGENT', None)
		models.PayCallBackLog.objects.create(remote_addr=remote_addr, server_port=server_port,
		                                     request_method=request_method, path_info=path_info, url_scheme=url_scheme,
		                                     query_string=query_string, request_body=request_body,
		                                     http_user_agent=http_user_agent)
		return True
	except:
		return False

class LogViews(View):
	def get(self,request,*args,**kwargs):
		true = {'code': 1000, 'message': '成功'}
		false = {'code': 1001, 'message': '失败'}
		if getdata(request):
			return HttpResponse(json.dumps(true,ensure_ascii=False))
		else:
			return HttpResponse(json.dumps(false,ensure_ascii=False))

	def post(self,request,*args,**kwargs):
		true = {'code': 1000, 'message': '成功'}
		false = {'code': 1001, 'message': '失败'}
		if getdata(request):
			return HttpResponse(json.dumps(true,ensure_ascii=False))
		else:
			return HttpResponse(json.dumps(false,ensure_ascii=False))


def paycallback(request):
	if request.method == 'GET':
		from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
		obj = models.PayCallBackLog.objects.all()
		limit = 1 # 设置每页的数量
		paginator = Paginator(obj, limit)  # 实例化一个分页对象
		page = request.GET.get('page')  # 获取页码
		try:
			obj = paginator.page(page)  # 获取某页对应的记录
		except PageNotAnInteger:  # 如果页码不是个整数
			obj = paginator.page(1)  # 取第一页的记录
		except EmptyPage:  # 如果页码太大，没有相应的记录
			obj = paginator.page(paginator.num_pages)  # 取最后一页的记录
		return render(request,'paycallback.html',{'obj':obj})

